import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: localStorage.getItem('token') || '',
    user: JSON.parse(localStorage.getItem('user') || '{}')
  },
  mutations: {
    userLogin(state, params) {
      state.user = params.user
      state.token = params.token
      localStorage.setItem('token', params.token)
      localStorage.setItem('user', JSON.stringify(params.user))
    },
    setState(state, params) {
      for (const key in state) {
        if (key == params.key) {
          state[key] = params.value
          localStorage.setItem(params.key, JSON.stringify(params.value))
        }
      }
    },
    setLStorage(state, params) {
      localStorage.setItem(params.key, params.value instanceof Object ? JSON.stringify(params.value) : params.value)
    },
    setSStorage(state, params) {
      sessionStorage.setItem(params.key, params.value instanceof Object ? JSON.stringify(params.value) : params.value)
    },
    getSStorage(state, params) {
      const temp: any = sessionStorage.getItem(params.key)
      return JSON.parse(temp)
    },
    getLStorage(state, params) {
      const temp: any = localStorage.getItem(params.key)
      return JSON.parse(temp)
    }
  },
  actions: {
    userLogin({ commit }, params) {
      commit('userLogin', params)
    },
    setState({ commit }, params) {
      commit('setState', params)
    }
  },
  modules: {}
})
